#!/bin/bash

FORMAT=".ppp"
if [ $# != 4 ]; then
	echo -e "Usage: $0 <Destination_Path> <List_File_Path> <Architecture> <Category> \n"
	exit
fi
if [ -d $1 ]; then
	echo "Destination Directory exists: Do you wish to remove it (y/n) ?"
	read ch
	if [ $ch = "y" ] || [ $ch = "Y" ]; then
		rm -rf $1
	fi
fi
mkdir -p $1 2> /dev/null
exec 3<&0
exec 0< $2
id_top=`echo "select id from category where name='$4'" | mysql -uweps -hterminator weps -s`
id_sys_soft=`echo "select id from category where name='System Software' && par_id='$id_top'" | mysql -uweps -hterminator weps -s`
while read -r line
do
NAME=$line
	#for i in `echo "select DISTINCT(pac_id) from file where name RLIKE ('$NAME')" | mysql -uweps -hterminator weps -s`
	for i in `echo "select DISTINCT(id) from package where name='$NAME' && cat_id='$id_sys_soft'" | mysql -uweps -hterminator weps -s`
		do
		PACKAGE=`echo "select name from file where id IN (select max(id) from file where pac_id=$i)" | mysql -uweps -hterminator weps -s`
		BASENAME=`basename $PACKAGE`
		PKGNAME=`echo $BASENAME | awk -F "-" '{ pkg=$1; for(f=2; f<=NF-2; f++) { pkg=pkg"-"$f } ; ver=NF-1; printf("%s\n", pkg);}'`
		if [[ $PACKAGE =~ $FORMAT ]] && [[ $PACKAGE =~ $3 ]] ; then
			if [ -f $1/$PACKAGE ]; then
				rm -f $1/$PACKAGE
			fi	
			echo $PKGNAME
			wget --directory-prefix=$1 http://terminator/var/www/weps/repository/$4/System%20Software/$PKGNAME/$PACKAGE  
		fi
	done
done
exec 0<&3
echo "Done"
